package com.zxk28.sqlbuilders;

public class SQLSelectBuilder {

	private String prefixClause = "SELECT";
	private String columnsClause = null;
	private String fromClause = null;
	private String whereClause = null;
	private String groupByClause = null;
	private String havingClause = null;
	private String orderByClause = null;

	public SQLSelectBuilder setColumns(String... columns) {
		this.columnsClause = " ";

		for (int i = 0; i < columns.length; i++) {
			this.columnsClause += columns[i];
			if (i < columns.length - 1)
				this.columnsClause += ", ";
		}

		return this;
	}

	public SQLSelectBuilder setSelectTable(String talbe) {
		this.fromClause = " FROM " + talbe;

		return this;
	}

	public SQLSelectBuilder setWhereClause(String where) {
		this.whereClause = " WHERE " + where;

		return this;
	}

	public SQLSelectBuilder setGroupBy(String... groupBy) {
		this.groupByClause = " GROUP BY ";

		for (int i = 0; i < groupBy.length; i++) {
			this.groupByClause += groupBy[i];
			if (i < groupBy.length - 1)
				this.groupByClause += ", ";
		}

		return this;
	}

	public SQLSelectBuilder setHaving(String having) {
		this.havingClause = " HAVING " + having;

		return this;
	}

	public SQLSelectBuilder setOrderBy(String... OrderByAndDirection) {
		this.orderByClause = " ORDER BY ";

		for (int i = 0; i < OrderByAndDirection.length; i += 2) {
			this.orderByClause += OrderByAndDirection[i].toString() + " "
					+ OrderByAndDirection[i + 1];
			if (i < OrderByAndDirection.length - 2)
				this.orderByClause += ", ";
		}

		return this;
	}

	public String getCmd() {

		if (columnsClause == null)
			return null;
		if (fromClause == null)
			return null;

		String cmd = prefixClause + columnsClause + fromClause;

		if (whereClause != null)
			cmd += whereClause;
		if (groupByClause != null)
			cmd += groupByClause;
		if (havingClause != null)
			cmd += havingClause;
		if (orderByClause != null)
			cmd += orderByClause;
		cmd += ";";
		
		return cmd;
	}

	@Override
	public String toString() {
		return getCmd();
	}
}
